package com.twu.biblioteca;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by Lukas on 1/11/14.
 */
public class UserDatabase {
    private ArrayList<User> users = new ArrayList<User>();

    public UserDatabase() {
        seedDatabase();
    }

    public Map<String, User> validate(String libraryNumber, String password) {
        Map<String, User> mapToBeReturned = new HashMap<String, User>();

        if(!checkNumberFormat(libraryNumber)) {
            mapToBeReturned.put("Invalid library number.", null);
            return mapToBeReturned;
        }

        for(User user : users) {
            if (user.getLibraryNumber().equals(libraryNumber) && user.getPassword().equals(password)) {
                mapToBeReturned.put("Valid login.", user);
                break;
            }
        }

        if(mapToBeReturned.isEmpty()) {
            mapToBeReturned.put("Invalid library number and password combination.", null);
        }

        return mapToBeReturned;
    }

    private Boolean checkNumberFormat(String libraryNumber) {
        String pattern = "\\d{3}-\\d{4}\\b";

        return libraryNumber.matches(pattern);
    }

    private void seedDatabase() {
        String[] testUserLibraryNumbers  = new String[] {"123-4567", "123-4568", "123-4569"};
        String[] testUserLibraryNames  = new String[] {"Lukas Ingelheim", "Martin Fowler", "Olivia Marsden"};
        String[] testUserLibraryEmails  = new String[] {"lingelheim@thoughtworks.com", "mfowler@thoughtworks.com", "omarsden@thoughtworks.com"};
        String[] testUserLibraryPhoneNumbers  = new String[] {"123-121212", "123-131313", "123-141414"};
        String[] testUserLibraryPasswords  = new String[] {"rightPassword","rightPassword", "rightPassword"};

        for(int i = 0; i < testUserLibraryNumbers.length; i++) {
            String libraryNumber  = testUserLibraryNumbers[i];
            String name  = testUserLibraryNames[i];
            String email  = testUserLibraryEmails[i];
            String address  = testUserLibraryPhoneNumbers[i];
            String password  = testUserLibraryPasswords[i];

            User newUser = new User(libraryNumber, name, email, address, password);
            addUser(newUser);
        }
    }

    private void addUser(User userToAdd) {
        users.add(userToAdd);
    }
}